package com.travel.user.controller;

import com.travel.common.base.BaseApiService;
import com.travel.common.base.Resp;
import com.travel.user.entity.User;
import com.travel.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @classDesc: 功能描述:()
 * @author:<a href="leeue@foxmail.com">李月</a>
 * @Version:v1.0
 * @createTime:2019年2月24日 下午5:35:34
 */

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户模块")
public class UserController {

	@Autowired
	UserService userService;

	@Autowired
	BaseApiService baseApiService;

	@ApiOperation(value = "登录接口")
	@ApiImplicitParam(name = "user", value = "用户实体类", dataType = "User", required = true)
	@PostMapping("/login")
	public Resp login(@RequestBody User user) {

		log.info("##########login登录接口被调用#########user{}", user);
		if (null == user) {
			return baseApiService.setResultError("用户信息为空!");
		}
		String name = user.getName();
		if (StringUtils.isEmpty(name)) {
			return baseApiService.setResultError("用户名为空");
		}
		String password = user.getPassword();
		if (StringUtils.isEmpty(password)) {
			return baseApiService.setResultError("用户密码为空");
		}
		String role = user.getRole();
		if (StringUtils.isEmpty(role)) {
			return baseApiService.setResultError("用户角色为空");
		}
		User findUser = userService.findUser(name, password, role);
		if (null == findUser) {
			return baseApiService.setResultError("该用户不存在或用户名或密码错误");
		}
		user.setPassword("");
		return baseApiService.setResultSuccess(findUser);
	}

	@ApiOperation(value = "测试接口")
	@RequestMapping(value = "/get", method = RequestMethod.GET)
	public Resp get() {
		return baseApiService.setResultSuccess();
	}

	@ApiOperation(value = "注册接口")
	@ApiImplicitParam(name = "user", value = "用户实体类", dataType = "User", required = true)
	@PostMapping(value = "/regist")
	public Resp regist(@RequestBody User user) {

		log.info("####调用regist注册接口####user{}", user);
		if (null == user) {
			return baseApiService.setResultError("用户信息为空!");
		}
		String name = user.getName();
		if (StringUtils.isEmpty(name)) {
			return baseApiService.setResultError("用户名为空");
		}
		String password = user.getPassword();
		if (StringUtils.isEmpty(password)) {
			return baseApiService.setResultError("用户密码为空");
		}
		String role = user.getRole();
		if (StringUtils.isEmpty(role)) {
			return baseApiService.setResultError("用户角色为空");
		}

		// 查看当前用户用户名有没有被注册过
		if (userService.findByName(user.getName()) != null) {
			return baseApiService.setResultError("该用户名已被注册!");
		}

		userService.saveUser(user);
		user = userService.findByName(user.getName());
		user.setPassword("");
		return baseApiService.setResultSuccess("注册成功", user);
	}

}
